package com.scs.application.core.mybatis.handlers;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.scs.application.core.model.DataEntity;
import com.scs.application.core.model.TreeEntity;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.core.utils.UserUtils;
import com.scs.application.modules.upms.security.UserPrincipal;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

public class DataEntityMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {

        if (!(metaObject.getOriginalObject() instanceof DataEntity)) {
            return;
        }

        DataEntity entity = (DataEntity) metaObject.getOriginalObject();

        entity.setGmtCreate(new Date());
        entity.setGmtModified(new Date());

        UserPrincipal user = UserUtils.currentUser();
        if (StringUtils.isBlank(entity.getCreator())) {
            entity.setCreator(user.getId());
        }
        if (StringUtils.isBlank(entity.getModifier())) {
            entity.setModifier(user.getId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (!(metaObject.getOriginalObject() instanceof MapperMethod.ParamMap)) {
            return;
        }

        MapperMethod.ParamMap originalObject = (MapperMethod.ParamMap) metaObject.getOriginalObject();
        if (!originalObject.containsKey(Constants.ENTITY)) {
            return;
        }

        // 获取到的为实体类
        Object param1 = originalObject.containsKey("param1") ? originalObject.get("param1") : originalObject.get(Constants.ENTITY);
        if (!(param1 instanceof DataEntity || param1 instanceof TreeEntity)) {
            return;
        }

        setFieldValByName("gmtModified", new Date(), metaObject);

        UserPrincipal user = UserUtils.currentUser();

        if(user != null) {
            setFieldValByName("creator", user.getId(), metaObject);
            setFieldValByName("modifier", user.getId(), metaObject);
        }

    }
}
